package com.xrh.xdemo.service;


import java.util.concurrent.atomic.AtomicBoolean;

import javax.annotation.Resource;

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import com.xrh.xdemo.service.service.MenuService;
import com.xrh.xdemo.service.service.SysRoleService;
import com.xrh.xdemo.service.utils.BeanTableUtils;
import com.xrh.xdemo.service.utils.ResourceFileUtils;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class SpringOnloadListener   implements ApplicationListener<ContextRefreshedEvent>{
	
	//初始化标志
	private static AtomicBoolean initFlag = new AtomicBoolean(false);
	
	@Resource
	Environment environment;
	
	@Resource
	SysRoleService sysRoleService;
	
	@Resource
	MenuService menuService;
	
	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		
		log.info("系统初始化start...");
		
		//已经初始化 , 则不再初始化
		if(!initFlag.compareAndSet(false , true))
			return;
		
		//若表不存在则创建
		createTableIfNoExist();
		
		//初始化系统角色
		sysRoleService.initRole();
		
		//初始化系统菜单
		menuService.initSysMenu();
		
		log.info("系统初始化end...");
		
		log.info("=======================================");
		
		log.info("接口文档地址:http://127.0.0.1:{}/doc.html", environment.getProperty("server.port"));
		log.info("登录页地址:http://127.0.0.1:{}/login/login.html", environment.getProperty("server.port"));
		
		log.info("=======================================");
		
	}
	
	/**
	 * @function 若表不存在则创建
	 * @author 肖荣辉
	 * @date 2023年12月20日
	*/
	public void createTableIfNoExist() {
		
		log.info("初始化数据库和表结构start");
		
		try {
			
		    //创建数据库
		    BeanTableUtils.createDatabase();
		    
			String ddl = ResourceFileUtils.loadFileAndReadString("/files/tables_ddl.txt");
			
			String[] ddlArr = ddl.split(";");
			
			for(String tableDDL : ddlArr) {
				
				if(StrUtil.isBlank(tableDDL)) continue;
			
				BeanTableUtils.createTable(tableDDL.trim());
			
			}
		
		} catch (Exception e) {
			log.error("创建库表发生异常 ==>" , e);
		}
		
		log.info("初始化数据库和表结构end");
	}

}
